﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace SeanLib.Helper
{
   public class HttpRequstHelper
    {
        public static string Get(string apiUrl)
        {
            using (var httpClient = new HttpClient())
            {
                var task = httpClient.GetAsync(apiUrl).Result;                
                if (!task.IsSuccessStatusCode)
                    throw new Exception("接口访问失败:" + task.StatusCode);
                return task.Content.ReadAsStringAsync().Result;                
            }
        }
        /// <summary>
        /// post
        /// </summary>
        /// <param name="apiUrl">地址</param>
        /// <param name="jsonString">参数</param>
        /// <param name="contentType">默认json</param>
        /// <returns></returns>
        public static string Post(string apiUrl, string jsonString, string contentType = "application/json")
        {
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            //创建HttpClient（注意传入HttpClientHandler）
            using (var http = new HttpClient(handler))
            {
                //var requestJson = JsonConvert.SerializeObject(jsonString);

                HttpContent httpContent = new StringContent(jsonString);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                //await异步等待回应
                var task = http.PostAsync(apiUrl, httpContent);
                var result = task.Result.Content.ReadAsStringAsync().Result;


                //确保HTTP成功状态值
                //task.Result.EnsureSuccessStatusCode();
                if (task.Result.IsSuccessStatusCode == false)
                    throw new Exception("接口访问失败:" + task.Result.StatusCode);
                return result;
            }
        }

    }
}
